import vuex from "vuex";
import Vue from "vue";

Vue.use(vuex);

const store = new vuex.Store({
  state: {
    products: [],
  },
  mutations: {
    // addcart(state,playload){
    //   state.products.push(playload);
    //   console.log(state.products);
    // }
    addcount(state,playload){
      for(let item of state.products){
        if(item.iid == playload.iid){
          // item.count += 1;
          Vue.set(item,"count",item.count+1);
        }
      }
      // console.log("addcount",state.products);
    },

    addproduct(state,playload){
      playload.count = 1;
      playload.isChecked = true;
      state.products.push(playload);
      // console.log("addproduct",state.products);
    },

    addproductnull(state,playload){
      playload.count = 1;
      playload.isChecked = true;
      state.products.push(playload);
      // console.log("null+",state.products);
    }
  },
  actions: {
    addcart(context,playload){
      // let flag = false;
      let oldproduct = null;
      if(context.state.products.length !== 0){
        for(let item of context.state.products){
          if(item.iid == playload.iid){
            oldproduct = item;
          }
        }
        if(oldproduct){
          context.commit("addcount",playload);
        }else{
          context.commit("addproduct",playload);
          
        }
      }else{
        context.commit("addproductnull",playload);  
      }
      
    }
  },
  getters: {
    cartlist(state){
      return state.products;
    }
  }
})

export default store;

